package beautiful.butterfly.drds.binlog.server;


import beautiful.butterfly.drds.binlog.consumer.ConsumerMananger;
import beautiful.butterfly.drds.binlog.netty.server.NettyServer;
import beautiful.butterfly.drds.binlog.operation.OperationServer;
import beautiful.butterfly.drds.binlog.utils.Constants;
import beautiful.butterfly.drds.binlog.utils.SqlUtils;
import beautiful.butterfly.drds.binlog.utils.TimeUtils;
import beautiful.butterfly.drds.binlog.zookeeper.MachineListener;
import beautiful.butterfly.drds.binlog.zookeeper.TaskListener;
import beautiful.butterfly.drds.binlog.zookeeper.ZooKeepers;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class MyServer
{


    static
    {
        // 加载1次就可以了,启动时加载mysql驱动程序，免得后面耗时
        SqlUtils.init();
        // 保证zk的任务节点存在
        ZooKeepers.ensurePersistentPathWithNoValue(Constants.ZK_NAMESPACE_TASKS);
        // 保证zk的机器节点存在
        ZooKeepers.ensurePersistentPathWithNoValue(Constants.ZK_NAMESPACE_MACHINES);
    }

    public static void main(String[] args) throws IOException
    {
        log.info("system begins...");
        // -1)先启动消费线程组
        ConsumerMananger.start();
        //
        // 0先启动Netty服务
        NettyServer.start();
        //
        //
        // 1启动Operation服务
        OperationServer.start();
        log.info("---------------------------------------");
        //
        //
        // 2
        // 2.1)注册machines监听器
        log.info("register machines listener ");
        if (false == ZooKeepers.registerPathChildrenCacheListener(Constants.ZK_NAMESPACE_MACHINES,
                MachineListener.getMachineListener().getPathChildrenCacheListener()))
        {
            log.info("fail to register task listener,system will exit(-1)");
            System.exit(-1);
        }
        //
        // 3注册tasks监听器,这个一定要放到最后，否则有问题
        log.info("register task listener ");
        if (false == ZooKeepers.registerPathChildrenCacheListener(Constants.ZK_NAMESPACE_TASKS,
                TaskListener.getTaskListener().getPathChildrenCacheListener()))
        {
            log.info("fail to register task listener,system will exit(-1)");
            System.exit(-1);
        }
        //
        //
        // 4本线程用来做前台线程
        while (true)
        {
            // 睡眠3秒
            TimeUtils.sleepSeconds(3);
        }
    }

}
